// 单纯的构造组件，但还需要上下文才可渲染
import { initExecute } from '../../utils/index.js';
import { NAME } from '../../consts/index.js';
// SpaceItem -> FormItem -> NodeItem
let uid = 1;
class BuildItem {
	constructor(hook, modules, param = {}) {
		this.J_uid = uid++;
		this.hook = hook;
		// hook中会用到该值
		this.param = param;
		this.modules = modules;
		this[NAME] = 'BuildItem';
	}
	init(info = {}) {
		this.info = info;
		return this;
	}
	call(ctx, value, o) {
		const that = this;
		const node = {
			is: that.hook.$m.$jiess().JiessComponent,
			setup() {
				if (value) {
					that.info.$name = 'value';
					o = { initialValues: { value }, ...o };
				}
				that.ctx = this;
				that.area = node.areaInstance = this.area(o);
				this.add(that.node(that.hook.hookItemCall(that)));
			}
		};
		return node;
	}
	useArea(area) {
		this.area = area;
		this.ctx = area.ctx;
		return this.spaceItem(this.hook.hookItemCall(this));
	}
	spaceItem({
		$if,
		$show,
		// ======================
		$spaceItemParam,
		$hasSpaceItem = true,
		$span,
		...o
	}) {
		if ($hasSpaceItem) {
			return {
				$if,
				$show,
				$span,
				children: this.formItem(o),
				is: this.hook.$m.$SpaceItem,
				...$spaceItemParam
			};
		} else {
			return this.formItem({ $if, $show, ...o });
		}

	}
	formItem({
		$if,
		$show,
		$rules,
		$label,
		$formItemParam,
		$hasFormItem = true,
		...o
	}) {
		if ($hasFormItem) {
			const { ctx, area, hook } = this;
			const { rule, hasRule = true } = area.param;
			// 属性配置
			let result = { $if, $show, label: $label };
			result = hook.hookFormItem(o.name, result);
			result = { ...result, ...$formItemParam };
			result = { ...result, is: hook.$m.FormItem };
			result = { ...result, children: this.node(o) };
			// 不需要校验的表单区，则移除FormItem的校验展示区
			if (hasRule) {
				result.rules = rule.init($rules, $label);
			} else {
				result.style = { marginBottom: 0 };
			}
			return result;
		} else {
			return this.node({ $if, $show, ...o });
		}
	}
	node({
		name,
		children,
		className,
		$slots,
		$brother,
		...attrs
	}) {
		const { ctx, area, hook, modules } = this;
		const { childsTarget, childsProxy } = area.param;
		// 对子项集合绑定响应式观察
		if (name) {
			// 初始化赋值，此时还未绑定观察器
			childsTarget[name] = children;
			// 对children使用观察器
			children = { $proxy: childsProxy, field: name };
		}
		attrs = {
			className: ['jiess-item', className],
			is: modules.is,
			children,
			...attrs
		};
		// 插槽始终注入内部元素中
		if ($slots) attrs.$slots = $slots;
		// 返回主体节点和兄弟节点的数组
		return [attrs, $brother];
	}
}
export default BuildItem;